<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="../js/jquery-1.11.2.js"></script>
    <title>Document</title>
</head>
<body>
    <h1> 异步请求 </h1>
    <script>
     let p1 = 'https://autumnfish.cn/api/joke/list?num=3';
    //  let task2 ="做饭";
    //  let task3 = "看书学习"

     /*
     $.ajax({
        url: task1,
        success: function(ret ){
            console.log(ret );
            $.ajax({
                url: task2,
                success: function(ret ){
                    console.log(ret );
                    $.ajax({
                        url: task3,
                        success: function(ret ){
                            console.log(ret );
                        }
                    })
                }
            })
        }
     })
     */
    // t1里有三个方法 then() ,catch() ,finally()

 function task1(){
    let t1 =  new Promise(function(a,b){
        console.log("任务1执行.....");
        //发请求
        setTimeout(function(){
            let n = Math.random();
            if(n> 0.5){
                a('成功的值'+ n);
            }else{
                b('失败的值' + n );
            }
        },3000);
     });
     return t1;
 }

 function task2(){
    let t2 =  new Promise(function(a,b){
        console.log("任务2执行.....");
        //发请求
        $.ajax({
            url: p1,
            success:function(ret){
                a(ret);
            }
        });
     });
     return t2;
 }

 function task3(){
    let t3 =  new Promise(function(a,b){
        console.log("任务3执行.....");
        //发请求
        setTimeout(function(){
           a('任务3已完成...');
        },3000);
     });
     return t3;
 }
    

    //  task1().then(function(ret){
    //     console.log( ret );
    //     //任务1 结束了
    //     return task2();
    //  }).then(function(ret){
    //     console.log("得到了笑话", ret );
    //     return task3();
    //  }).then( function(ret){
    //     console.log( ret );
    //  })

    // es7 Promise 再次优化 
    async function test(){
        let ok = await task1();
        console.log( ok );
        ok = await task2();
        console.log( ok );
        ok = await task3();
        console.log( ok );
    }

    test();

    </script>
</body>
</html>